package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.minio.MinioProperties;
import com.atguigu.lease.web.admin.service.FileService;
import io.minio.*;
import io.minio.errors.*;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {
    @Autowired
    private MinioClient minioClient;
    @Autowired
    private MinioProperties minioProperties;

    @Override
    public String upload(MultipartFile file) {
        String bucketName = minioProperties.getBucketName();
        makeBucket(bucketName);
        String fileName = PutObject(file, bucketName);

        return minioProperties.getEndpoint() +"/"+ bucketName +"/"+ fileName;
    }

    private String PutObject(MultipartFile file, String bucketName) {
        try {
            String filename = file.getOriginalFilename();
            String suff = filename.substring(filename.lastIndexOf("."));
            String uuid = UUID.randomUUID().toString().replace("-","");
            String datePath = new SimpleDateFormat("yyyy/MM/").format(new Date());
            filename = datePath + uuid + suff;
            InputStream stream = file.getInputStream();
            String contentType = file.getContentType();
            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(filename)
                    .stream(stream, file.getSize(), -1)
                    .contentType(contentType)
                    .build();
            minioClient.putObject(putObjectArgs);
            return filename;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private void makeBucket(String bucketName) {
        try {
            BucketExistsArgs bucketExistsArgs = BucketExistsArgs.builder()
                    .bucket(bucketName)
                    .build();
            if ( ! minioClient.bucketExists(bucketExistsArgs)) {
                MakeBucketArgs makeBucketArgs = MakeBucketArgs.builder()
                        .bucket(bucketName)
                        .build();
                minioClient.makeBucket(makeBucketArgs);
                String config = """
                        {
                          "Statement" : [ {
                            "Action" : "s3:GetObject",
                            "Effect" : "Allow",
                            "Principal" : "*",
                            "Resource" : "arn:aws:s3:::%s/*"
                          } ],
                          "Version" : "2012-10-17"
                        }
                        """.formatted(bucketName);
                SetBucketPolicyArgs setBucketPolicyArgs = SetBucketPolicyArgs.builder()
                        .bucket(bucketName)
                        .config(config)
                        .build();
                minioClient.setBucketPolicy(setBucketPolicyArgs);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
